<template>
  <div>
    <!-- <div class="context-menu-trigger">右击我试试</div> -->
    <div
      v-if="showContextMenu"
      :style="menuStyle"
      class="context-menu"
    >
      <template v-if="cellOperate">
        <div
          v-if="isMarge"
          @click="mergeCell()"
        >
          合并单元格
        </div>
        <div
          v-else
          @click="splitCell()"
        >
          拆分单元格
        </div>
      </template>
      <div @click="delRow()">删除本行</div>
      <div @click="delCol()">删除本列</div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      showContextMenu: false,
      menuStyle: {
        top: '0px',
        left: '0px',
      },
      isMarge: true,
      cellOperate: false,
    }
  },
  methods: {
    openContextMenu(event, flag, cellOperate) {
      this.isMarge = !flag
      this.cellOperate = !cellOperate
      this.menuStyle.top = `${event.clientY}px`
      this.menuStyle.left = `${event.clientX}px`
      this.menuStyle.position = 'fixed'
      this.menuStyle.zIndex = 9999999
      this.showContextMenu = true

      // 监听一次点击事件，用于关闭菜单
      window.addEventListener('click', this.closeContextMenu, { once: true })
    },
    mergeCell() {
      this.$emit('mergeCell')
    },
    splitCell() {
      this.$emit('splitCell')
    },
    delRow() {
      this.$emit('delRow')
    },
    delCol() {
      this.$emit('delCol')
    },
    closeContextMenu() {
      this.showContextMenu = false
    },
    menuItemClicked(item) {
      console.log(`${item} 被点击了`)
      this.closeContextMenu()
    },
  },
}
</script>

<style scoped>
.context-menu {
  position: absolute;
  border: 1px solid #ccc;
  background-color: #fff;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.15);
}

.context-menu div {
  padding: 8px;
  cursor: pointer;
}

.context-menu div:hover {
  background-color: #f5f5f5;
}
</style>
